package club.haomoon.front.service.impl;

import club.haomoon.core.common.PageResult;
import club.haomoon.core.entity.log.UserAccountLogData;
import club.haomoon.core.enums.AccountLogEnum;
import club.haomoon.core.mapper.log.UserAccountLogDataMapper;
import club.haomoon.core.util.DateUtil;
import club.haomoon.core.util.StringUtils;
import club.haomoon.front.data.user.UserAccountListData;
import club.haomoon.front.service.IUserAccountLogService;
import club.haomoon.front.validate.common.PageValidate;
import club.haomoon.front.validate.users.UserAccountLogSearchValidate;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * -------------------------
 * @Description:  用户服务实现类
 * @Author: Wangjianwei
 * @Date: 2025/02/24 15:47
 * -------------------------
 */
@Service
public class UserAccountLogServiceImpl implements IUserAccountLogService {

    @Resource
    UserAccountLogDataMapper userAccountLogMapper;

    @Override
    public PageResult<UserAccountListData> lists(PageValidate pageValidate, UserAccountLogSearchValidate searchValidate) {
        Integer pageNo   = pageValidate.getPage_no();
        Integer pageSize = pageValidate.getPage_size();

        QueryWrapper<UserAccountLogData> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("delete_time");
        queryWrapper.eq("user_id", searchValidate.getUserId());
        if (StringUtils.isNotEmpty(searchValidate.getType()) && searchValidate.getType().equals("um")) {
            queryWrapper.in("change_type", AccountLogEnum.getUserMoneyChangeType());
        }

        if (StringUtils.isNotNull(searchValidate.getAction())) {
            queryWrapper.eq("action", searchValidate.getAction());
        }

        queryWrapper.orderByDesc("id");
        IPage<UserAccountLogData> iPage = userAccountLogMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
        List<UserAccountListData> list = new LinkedList<>();
        for (UserAccountLogData item : iPage.getRecords()) {
            UserAccountListData vo = new UserAccountListData();
            BeanUtils.copyProperties(item, vo);
            vo.setTypeDesc(AccountLogEnum.getChangeTypeDesc(item.getChangeType()));
            String symbol = item.getAction().equals(AccountLogEnum.DEC.getCode()) ? "-" : "+";
            vo.setChangeAmountDesc(symbol + item.getChangeAmount());
            vo.setCreateTime(DateUtil.timestampToDate(item.getCreateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }
}
